<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>   
</head>

<body>
    <h1>取消练习</h1>
    <input type="text" id="ipt">
    <button id="btn">提交</button>
    <button id="cancel">取消请求</button>

    <script>
        const myAxios = axios.create({
            baseURL: '/', //配置公共路径
            timeout: 10000, //配置超时时间
            headers: {} //配置请求头
        })

        const oIpt = document.getElementById('ipt')
        const oBtn = document.getElementById('btn');
        const oCancel = document.getElementById('cancel');

        //拿到一个取消请求的对象(是一个构造函数)
        const CancelToken = axios.CancelToken;
        let cancel = null;
        oBtn.onclick = async function () {
            const iptValue = oIpt.value;
            try {
                const result = await myAxios.get('/userLazy', {
                    params: {
                        userId: iptValue
                    },
                    //在配置对象中配置一个cancelToken的配置项,值是实例化的CancelToken对象
                    cancelToken: new CancelToken((c) => {
                        console.log(c);
                        cancel = c;
                    })
                })
                console.log(result, 'result');
            } catch (e) {
                console.log('出现错误', e.message);
            }
        }

        //取消请求点击事件
        oCancel.onclick = function () {
            cancel()
        }
    </script>
</body>

</html>